package com.ckjava.test.cas;

import com.ckjava.xutils.StringUtils;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 在服务器端 cas 登录页面成功后， cas 组件自动根据 ticket 获取用户信息
 */
public class CustomUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        System.out.println("当前的用户名是："+token.getName());
        /*这里我为了方便，就直接返回一个用户信息，实际当中这里修改为查询数据库或者调用服务什么的来获取用户信息*/

        Map<String, Object> userData = token.getAssertion().getPrincipal().getAttributes();
        userData.forEach((key, value) -> {
            System.out.println(String.format("key:%s,value:%s", key, value));
        });

        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(StringUtils.getStr(userData.get("displayName")));
        userInfo.setName(StringUtils.getStr(userData.get("name")));

        //CollectionUtils<GrantedAuthority> authorities = token.getAuthorities();
        Set<AuthorityInfo> authorities = new HashSet<>();
        AuthorityInfo authorityInfo = new AuthorityInfo("TEST");
        authorities.add(authorityInfo);
        userInfo.setAuthorities(authorities);
        return userInfo;
    }
}
